<?php
declare (strict_types=1);

namespace app\admin\logic\market\ticket;

use app\admin\logic\system\Log;
use app\admin\model\market\ticket\Ticket as TicketModel;
use app\common\exception\LogicException;
use app\course\logic\coupon\CouponUser;
use think\facade\Request;

/**
 * 活动逻辑层
 */
class Ticket extends TicketModel
{
    /**
     * 获取列表
     *
     * @param array $map
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function getList(array $map = [])
    {
        return $this->where($map)->order('create_time', 'DESC')->paginate($this->getListRows());
    }

    /**
     * created
     *
     * @param array $data
     * @return int
     */
    public function created(array $data)
    {
        // 验证数据
        $this->getValidate()->scene('create')->failException()->check($data);

        // $saved = [
        //     'mhm_id'           => request()->mhm_id,
        //     'pid'              => ,
        //     'issue_no'         => $data['issue_no'] ?? '',
        //     'target_user_type' => $data['target_user_type'] ?? 0
        // ];

        $pid = $data['pid'] ?? 0;
        // 是否选中了往期活动
        if ($pid <= 0) {
            // 未指定往期活动，表示新建活动
            // 新建活动
            $data['pid'] = $this->insert([
                'mhm_id'      => request()->mhm_id,
                'pid'         => 0,
                'title'       => $data['title'],
                'create_time' => Request::time(),
                'update_time' => Request::time(),
            ], true);

            $title = $data['title'];
        } else {
            $title = $this->where('id', $pid)->value('title');
        }

        // 新建期
        $saved = [
            'mhm_id'           => request()->mhm_id,
            'pid'              => $data['pid'],
            'issue_no'         => $data['issue_no'],
            'target_user_type' => $data['target_user_type']
        ];

        // 创建成功
        if (!$this->create($saved)) {
            throw new LogicException('创建失败');
        }

        Log::write('新建活动【' . $title . ' - ' . $saved['issue_no'] . '】', 'market_ticket', 'create', true);

        // 返回值
        return true;
    }

    /**
     * getInfoById
     *
     * @param int $id
     * @return Ticket|array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getInfoById(int $id)
    {
        $info = $this->where('id', $id)->find();
        if ($info && $info->pid > 0) {
            $info->title = $this->where('id', $info->pid)->value('title');
        }

        return $info;
    }

    /**
     * updated
     *
     * @param $id
     * @param $data
     * @return Ticket|array|\think\Model
     */
    public function updated($id, array $data)
    {
        $ticket = $this->where('id', $id)->findOrFail();
        if (isset($data['title'])) {
            $ticket->title = $data['title'];
        }

        if (isset($data['status'])) {
            $ticket->status = intval($data['status']) == 1 ? 1 : 0;
        }

        if (!$ticket->save()) {
            throw new LogicException('修改失败');

        }

        if ($ticket->pid === 0) {
            Log::write('编辑活动【' . $ticket->title . '】', 'market_ticket', 'update', true);
        } else {
            Log::write('编辑活动【' . $ticket->title . ' - ' . $ticket->issue_no . '】', 'market_ticket', 'update', true);
        }

        return $ticket;
    }

    /**
     * updated
     *
     * @param $id
     * @param $data
     * @return Ticket|array|\think\Model
     */
    public function updatedBy($id, $field, $value)
    {
        $ticket = $this->where('id', $id)->findOrFail();

        $ticket->$field = $value;

        if (!$ticket->save()) {
            throw new LogicException('修改失败');
        }

        if ($ticket->pid === 0) {
            Log::write('编辑活动【' . $ticket->title . '】', 'market_ticket', 'update', true);
        } else {
            Log::write('编辑活动【' . $ticket->title . ' - ' . $ticket->issue_no . '】', 'market_ticket', 'update', true);
        }

        return $ticket;
    }

    /**
     * deleted
     *
     * @param $id
     */
    public function deleted($id)
    {
        $ticket = $this->where('id', $id)->whereOr('pid', $id)->selectOrFail();
        $this->startTrans();
        try {
            $ticket->each(function ($i) {
                $title   = $i->title;
                $issueNo = $i->pid > 0 ? ' - ' . $i->issue_no : '';
                // 处理删除
                if (!$i->delete()) throw new LogicException("删除失败");
                // 处理删除
                if ($i->pid === 0) {
                    Log::write('删除活动【' . $title . '】', 'market_ticket', 'delete', true);
                } else {
                    // 删除对应活动券
                    $TicketCoupon = app(TicketCoupon::class)->where('ticket_id', $i->id)->select();
                    $TicketCoupon->each(function ($t) {
                        if (!$t->delete()) throw new LogicException("删除失败");
                        // 删除用户领取的活动券
                        $ticketId = $t->id;
                        $r        = CouponUser::destroy(function ($query) use ($ticketId) {
                            $query->where('ticket_id', $ticketId);
                        });
                        if (!$r) throw new LogicException("删除失败");
                    });
                    Log::write('删除活动【' . $title . $issueNo . '】', 'market_ticket', 'delete', true);
                }
            });
            $this->commit();
        } catch (LogicException $e) {
            $this->rollback();
            throw new LogicException($e->getMessage());
        }

    }

    /**
     * 搜索
     *
     * @param string $keyword
     * @param int    $limit
     * @return Ticket[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function search(string $keyword, int $limit = 15)
    {
        return $this->whereLike('title', '%' . $keyword . '%')->field(['title', 'id' => 'value'])->limit($limit)->select();
    }

}
